import re
import urlparse
import utils


def transform(content, url, seed, options=None):
    content = replace_links(content, url, seed, options)
    content = inject_scripts(content)
    content = inject_body(content, url, seed, options)
    return content

RE_LINK = re.compile(r'''\b(href|src|action)\s*=\s*(["']?)([-\w_+%?=.:;/#!@&]+)\2|url\(([-\w_+%?=.:;/#!@]+)\)''',
                     re.I)
def replace_links(content, url, seed, options=None):
    def sub_link(m):
        def encode_link(link):
            link = urlparse.urljoin(url, link)
            return '/p/' + str(utils.encode_url(link, seed, options)) + '/'

        if m.group(3):
            link = m.group(3)
            if 'javascript:' in link.lower():
                return m.group()

            # replace the link
            quote = m.group(2)
            return m.group(1) + '=' + quote + encode_link(link) + quote
        else:
            link = m.group(4)
            return 'url(%s)' % encode_link(link)
    return RE_LINK.sub(sub_link, content)

RE_HEAD = re.compile(r'<head>(.*?)</head>', re.I|re.S)
def inject_scripts(content):
    return RE_HEAD.sub('''<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" language="javascript" src="/static/js/onlineproxy.js"></script>
<link type="text/css" rel="stylesheet" href="/static/css/styles.css"></link>
\\1</head>''', content)


RE_BODY = re.compile(r'(<body.*?>)(.*)</body>', re.I|re.S)
def inject_body(content, url, seed, options):
    return RE_BODY.sub('''<body>
    <form id="p4y_topform" action="/p/" method="get" onsubmit="return marlon.onlineproxy.sbmtProxy(this);">
		<div>
        <input type="hidden" name="seed" value="%s"/>
        <input type="text" name="url" size="80" value="%s"/>
        <label><a href="#" onclick="marlon.onlineproxy.sbmtProxy(); return false;">GO</a></label>
		</div>
    </form>
   \\2</body>''' % (str(seed), str(url)), content)

